package ca.cbc.medialib.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * =============================================
 * Copyright (c) 2011 Canadian Broadcasting Corporation.
 * All rights reserved.
 * <p/>
 * ca.cbc.medialib.util.HibernateUtil.java
 * =============================================
 * <p/>
 * PURPOSE:	Manages Hibernate Session Factory and Session
 * <p/>
 * =============================================
 * MODIFICATION		LOG	DATE		REASON / Change Request #
 * Liu Yang			Jun 22, 2011	Initial file creation
 * =============================================
 */
public enum SessionFactoryUtil {
	INSTANCE;
    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
		return this.getSessionFactory(null);
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public SessionFactory getSessionFactory(String configFile) {
        if (sessionFactory == null) {
            logger.debug("No SessionFactory found, create session factory.");
            Configuration cfg = null;
            if (configFile == null) {
                cfg = new Configuration().configure();
            } else {
                cfg = new Configuration().configure(configFile);
            }
            this.setSessionFactory(cfg.buildSessionFactory());
        }
        return sessionFactory;
    }
	
    public void shutdown() {
        if (sessionFactory != null) {
            sessionFactory.close();
            sessionFactory = null;
            logger.debug("*** Hibernate session is now closed.");
        }
    }
}
